package com.openai.client;

import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.core.http.AsyncStreamResponse;
import com.openai.models.ChatCompletionChunk;
import com.openai.models.ChatCompletionCreateParams;
import com.openai.models.ChatCompletionMessageParam;
import com.openai.models.ChatCompletionStreamOptions;
import com.openai.models.ChatCompletionUserMessageParam;
import org.apache.commons.lang3.time.StopWatch;
import org.jetbrains.annotations.NotNull;

import java.text.MessageFormat;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author 李林峰
 */
public class Main {

    public static void main(String[] args) throws InterruptedException {
        String apiKey = "";

        StopWatch stopWatch = StopWatch.create();
        stopWatch.start();
        AsyncStreamResponse<ChatCompletionChunk> streamResponse = OpenAIOkHttpClientAsync
            .builder()
            .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
            .apiKey(apiKey)
            .build()
            .chat()
            .completions()
            .createStreaming(
                ChatCompletionCreateParams
                    .builder()
                    .model("qwen-max")
                    .streamOptions(ChatCompletionStreamOptions.builder().includeUsage(true).build())
                    .addMessage(
                        ChatCompletionMessageParam.ofChatCompletionUserMessageParam(
                            ChatCompletionUserMessageParam.builder().role(ChatCompletionUserMessageParam.Role.USER).content("做一下云南旅游").build()
                        )
                    )
                    .build()
            );
        System.out.println(MessageFormat.format("请求结束时间：{0}",stopWatch.getTime(TimeUnit.MILLISECONDS)));
        streamResponse.subscribe(
            new AsyncStreamResponse.Handler<>() {
                @Override
                public void onNext(ChatCompletionChunk chunk) {
                    System.out.println(MessageFormat.format("获取片段时间：{0} {1}", stopWatch.getTime(TimeUnit.MILLISECONDS), chunk));
                }

                @Override
                public void onComplete(@NotNull Optional<Throwable> error) {
                    if (error.isEmpty()) {
                        System.out.println("结束");
                    } else {
                        System.out.println("出现异常"+ error.get().getMessage());
                    }
                }
            }
        );
        System.out.println(MessageFormat.format("代码执行结束时间：{0}",stopWatch.getTime(TimeUnit.MILLISECONDS)));
        Thread.sleep(5000);
    }
}
